import { type Directive } from 'vue';
import vtTouchCom from '../v-drag/vtTouchCom.ts';

interface LongpressBindingValue {
    long?: boolean;
    prevent?: boolean;
    press?: (event: Event) => void;
    hold?: (event: Event) => void;
    release?: (event: Event) => void;
}

interface PressHandlers {
    down: (event: Event) => void;
    up: (event: Event) => void;
    move?: (event: Event) => void;
}

const vLongpress: Directive = {
    mounted(el: HTMLElement, binding: { value: LongpressBindingValue }) {
        const { vtTouchInit, vtTouchDown, vtTouchUp } = vtTouchCom(
            el,
            binding.value
        );
        vtTouchInit(el);

        // 配置参数
        const holdDuration = binding.value.long ? 1000 : 500;
        let holdTimer: number | null = null;
        let isPressed = false;
        let startX = 0;
        let startY = 0;
        const MOVE_THRESHOLD = 10; // 移动阈值，防止误触

        // 按下事件处理
        const handlePointerDown = (e: any) => {
            vtTouchDown(el);
            if (binding.value.prevent) {
                e.preventDefault();
            }

            isPressed = true;

            // 记录起始位置
            if (e?.touches?.[0]) {
                startX = e.touches[0].clientX;
                startY = e.touches[0].clientY;
            } else {
                startX = e.clientX;
                startY = e.clientY;
            }

            // 触发按下事件
            if (binding.value.press) {
                binding.value.press(e);
            }

            // 设置长按计时器
            holdTimer = window.setTimeout(() => {
                if (isPressed && binding.value.hold) {
                    binding.value.hold(e);
                }
            }, holdDuration);
        };

        // 抬起/取消事件处理
        const handlePointerUp = (e: Event) => {
            vtTouchUp(el);
            if (holdTimer !== null) {
                clearTimeout(holdTimer);
                holdTimer = null;
            }

            if (isPressed) {
                if (binding.value.release) {
                    binding.value.release(e);
                }
                isPressed = false;
            }
        };

        // 移动事件处理（防止误触）
        const handlePointerMove = (e: any) => {
            if (!isPressed) return;

            let currentX = 0;
            let currentY = 0;

            if (e?.touches?.[0]) {
                currentX = e.touches[0].clientX;
                currentY = e.touches[0].clientY;
            } else {
                currentX = e.clientX;
                currentY = e.clientY;
            }

            // 如果移动超过阈值，则取消长按
            const moveX = Math.abs(currentX - startX);
            const moveY = Math.abs(currentY - startY);

            if (moveX > MOVE_THRESHOLD || moveY > MOVE_THRESHOLD) {
                if (holdTimer !== null) {
                    clearTimeout(holdTimer);
                    holdTimer = null;
                }
                isPressed = false;
            }
        };

        // 存储事件处理器引用，便于销毁
        const handlers: PressHandlers = {
            down: handlePointerDown,
            up: handlePointerUp,
            move: handlePointerMove,
        };

        // 添加事件监听器
        el.addEventListener('pointerdown', handlePointerDown);
        el.addEventListener('pointerup', handlePointerUp);
        el.addEventListener('pointercancel', handlePointerUp);
        el.addEventListener('pointerleave', handlePointerUp);

        // 存储处理器引用和设备类型
        (el as any)._pressHandlers = handlers;
    },

    unmounted(el: HTMLElement) {
        const handlers = (el as any)._pressHandlers as
            | PressHandlers
            | undefined;

        if (handlers) {
            el.removeEventListener('pointerdown', handlers.down);
            el.removeEventListener('pointerup', handlers.up);
            el.removeEventListener('pointercancel', handlers.up);
            el.removeEventListener('pointerleave', handlers.up);

            // 清理引用
            delete (el as any)._pressHandlers;
        }
    },
};

export default vLongpress;
